#include "barchartwidget.h"

BarChartWidget::BarChartWidget(QWidget *parent) : QWidget(parent)
{
    // 创建图表
    m_chart = new QChart();
    m_chart->setTitle("环境数据概览");
    m_chart->legend()->setVisible(true);
    m_chart->legend()->setAlignment(Qt::AlignBottom);
    // 创建柱状图系列
    m_barSet = new QBarSet("当前值");
    // 创建柱状图序列
    m_barSeries = new QBarSeries();
    m_barSeries->append(m_barSet);
    m_chart->addSeries(m_barSeries);
    // 创建坐标轴
    m_axisX = new QBarCategoryAxis();
    m_axisX->append("光照");
    m_axisX->append("温度");
    m_axisX->append("湿度");
    m_axisY = new QValueAxis();
    m_axisY->setTitleText("值");
    m_chart->addAxis(m_axisX, Qt::AlignBottom);
    m_chart->addAxis(m_axisY, Qt::AlignLeft);
    m_barSeries->attachAxis(m_axisX);
    m_barSeries->attachAxis(m_axisY);
    // 设置柱状图颜色
    QList<QColor> colors = {QColor(255, 165, 0), QColor(255, 0, 0), QColor(0, 0, 255)};
    //m_barSeries->setColors(colors);
    // 设置坐标轴范围
    m_axisY->setRange(0, 1500);
    // 创建图表视图
    m_chartView = new QChartView(m_chart, this);
    m_chartView->setRenderHint(QPainter::Antialiasing);
    m_chartView->setMinimumSize(300, 200);
    // 创建布局
    QVBoxLayout *layout = new QVBoxLayout(this);
    layout->addWidget(m_chartView);
    layout->setContentsMargins(0, 0, 0, 0);
}
void BarChartWidget::updateChart(const DataPoint &data){
    // 清空现有数据
    m_barSet->remove(0, m_barSet->count());
    // 添加新数据点
    m_barSet->append(data.light);
    m_barSet->append(data.temperature);
    m_barSet->append(data.humidity);
    // 动态调整Y轴范围以适应数据
    updateYAxisRange();
}

void BarChartWidget::updateYAxisRange(){
    // 计算所有数据点的最大值
    qreal maxValue = 0;
    for (int i = 0; i < m_barSet->count(); ++i) {
        maxValue = qMax(maxValue, m_barSet->at(i));
    }
    // 设置Y轴范围，留出一些余量
    m_axisY->setRange(0, maxValue * 1.1);
}
